import React from 'react';
import './MiniteChart.scss';
import MiniLayer from 'ochart/layer/MiniLayer';
import Canvas from 'ochart/core/Canvas';
import AxisLayer from 'ochart/layer/AxisLayer';
import Polygon from 'ochart/base/Polygon';
import Point from "@/ochart/core/Point";

export default class MiniteChart extends React.Component {
    constructor(props) {
        super(props);
        this.chartRef = React.createRef();
    }

    componentWillReceiveProps(nextProps, nextContext) {
        const { data = [], lastClose = 0, timesNum = 24 * 60 * 60 } = nextProps;
        if (data !== this.props.data || lastClose !== this.props.lastClose || timesNum !== this.props.timesNum) {
            this.miniLayer.data = data;
            this.miniLayer.lastClose = lastClose;
            this.miniLayer.timesNum = timesNum;
            this.miniLayer.make();
            console.log(this.miniLayer);
            this.canvas.paint();
        }
    }


    componentDidMount() {
        const { data = [], lastClose = 0, timesNum = 24 * 60 * 60 } = this.props;
        this.canvas = new Canvas({
            ele: this.chartRef.current,
            canAction: false
        });

        this.axisLayer = new AxisLayer(this.canvas, {
            yAxisMax: 100,
            yAxisMin: 0,
            xAxisLabels: [],
            xAxisPosition: AxisLayer.AxisPosition.BLOCK,
            xAxisGraduations: 5,
            yAxisGraduations: 3,
            yAxisRender: (data) => {
                return {
                    text: parseFloat(data).toFixed(2),
                    size: 20,
                }
            }
        });
        this.miniLayer = new MiniLayer(this.canvas, {
            width: this.canvas.width,
            height: this.canvas.height - 160,
            timesNum: timesNum,
            data,
            lastClose
        });
        this.miniLayer.setPosition(0, 80);
        this.polygon = new Polygon(this.canvas, {
            color: '#FFFFFF'
        });
        this.polygon.alpha = 0.1;
        this.miniLayer.setOnMaked((option) => {
            const { points, xStep, yStep, pcg, lastClose } = option;
            let yAxisMax = lastClose + 80 / yStep + pcg;
            let yAxisMin = lastClose - 80 / yStep - pcg;
            this.axisLayer.yAxisMax =  yAxisMax;
            this.axisLayer.yAxisMin = yAxisMin;
            this.axisLayer.make();
            this.polygon.points = [new Point(0, 0)].concat(points, [new Point(points[points.length - 1].x, 0)]);
        });
        
        this.miniLayer.make();
        this.canvas.addChild(this.miniLayer, this.polygon, this.axisLayer);
        this.canvas.paint();
    }

    render() {
        const { className = '' } = this.props;
        return (
            <div ref={this.chartRef} className={className} />
        )
    }
}
